package com.djsearch.ui;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.djsearch.DJSearchApp;
import com.djsearch.R;
import com.djsearch.adapter.MainGridViewAdapter;
import com.djsearch.adapter.MainGridViewOtherAdapter;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.widget.MyDialog;
import com.djsearch.widget.ScrollLayout;

/**
 * 主界面
 * 
 * @author yinxing
 * @author chenyang2
 * 
 */
public class MainActivity extends BaseActivity {
	private static boolean mIsStart = false;
	private GridView mainGridView, mainGridViewOther;
	private Context mContext;
    
	private RelativeLayout cityNameLocationLayout, mainCenterLayout;// 底部布局，中间布局
	private Button goGroupShopBtn, loginBtn; // 点击进入团购按钮,登录按钮
	private ScrollLayout scrollLayout;
	private ImageView dotFirstImg, dotSecImg;

	// 定位信息
	private TextView locationDetail,checkCityName;
	private LocationClient mLocClient;
	private Button mainLocationBtn,searchBtn;
	private Vibrator mVibrator;
	private RelativeLayout locationBtnLayout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		mContext = this;
		// 初始化主界面
		initView();
		// 初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}

	void initView() {
		mainGridView = (GridView) findViewById(R.id.mainGridView);
		mainGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mainGridView.setVerticalScrollBarEnabled(false);
		mainGridView.setAdapter(new MainGridViewAdapter(mContext));

		mainGridViewOther = (GridView) findViewById(R.id.mainGridViewOther);
		mainGridViewOther.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mainGridViewOther.setAdapter(new MainGridViewOtherAdapter(mContext));

//		cityNameLocationLayout = (RelativeLayout) findViewById(R.id.cityNameLocation);
		
		checkCityName = (TextView)findViewById(R.id.checkCityName);
		
		mainCenterLayout = (RelativeLayout) findViewById(R.id.mainCenterLayout);
		scrollLayout = (ScrollLayout) findViewById(R.id.ScrollLayoutTest);
		scrollLayout.setToScreen(whichScreen);

		setMainCenterLayout(mainCenterLayout);
		// setMainCenterLayout(scrollLayout);
		loginBtn = (Button) findViewById(R.id.loginBtn);
		searchBtn = (Button)findViewById(R.id.searchBtn);
		mainLocationBtn = (Button) findViewById(R.id.mainLocationBtn);
		locationDetail = (TextView) findViewById(R.id.locationDetail);
		dotFirstImg = (ImageView) findViewById(R.id.dotImageViewOne);
		dotSecImg = (ImageView) findViewById(R.id.dotImageViewTwo);
		if (whichScreen == 0) {
			dotFirstImg.setImageResource(R.drawable.dian_pink);
			dotSecImg.setImageResource(R.drawable.dot_white);
		} else if (whichScreen == 1) {
			dotFirstImg.setImageResource(R.drawable.dot_white);
			dotSecImg.setImageResource(R.drawable.dian_pink);
		}
		
		locationBtnLayout = (RelativeLayout)findViewById(R.id.locationBtnLayout);
		
		SharedPreferences sharedata = getSharedPreferences("LOC", 0);
		String locDetail = sharedata.getString("addr", "北京");
		locationDetail.setText(locDetail);
		((DJSearchApp) getApplication()).mTv = locationDetail;
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean("isLogined", false).commit();
		loginOwn();//自动登录
	}

	private void loginOwn() {
		if (preferences.getBoolean("isLoginChecked", false)) {
			requestLogin();
			
		} else {
			return;
		}
		
	}

	void initOnClick() {
		/*cityNameLocationLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popWindow(v,checkCityName);
			}
		});*/

		
		searchBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, WanNengSearchActivity.class, 0);
			}
		});
		
		// 进入登录页面
		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isLogin()) {

					AlertDialog.Builder builder = new Builder(mContext);
					builder.setMessage("确认注销登录吗？");
				    builder.setTitle("提示");
					builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							SharedPreferences.Editor editor = preferences.edit();
							editor.putBoolean("isLogined", false).commit();
							loginBtn.setText("登录");
						}
					});
			        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});

				    builder.create().show();
				
				} else {
					startActivity(MainActivity.this, LoginActivity.class, 0);
				}
				
			}
		});

		// 定位按钮
//		mainLocationBtn.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				showDialog("正在加载地图...");
//				mLocClient.start();
//				startActivity(MainActivity.this, LocInfoActivity.class, 0);
//				
//			}
//		});

		locationBtnLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog("正在加载地图...");
				mLocClient.start();
				startActivity(MainActivity.this, LocInfoActivity.class, 0);
				
			}
		});
		
		scrollLayout
				.setOnScrollToScreen(new ScrollLayout.OnScrollToScreenListener() {

					@Override
					public void doAction(int whichScreen) {
						if (whichScreen == 0) {
							dotFirstImg.setImageResource(R.drawable.dian_pink);
							dotSecImg.setImageResource(R.drawable.dot_white);
						} else if (whichScreen == 1) {
							dotFirstImg.setImageResource(R.drawable.dot_white);
							dotSecImg.setImageResource(R.drawable.dian_pink);
						}

					}
				});
	}

	@Override
	void initHandler() {
		mLocClient = ((DJSearchApp) getApplication()).mLocationClient;
		mVibrator = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);
		((DJSearchApp) getApplication()).mVibrator = mVibrator;
		if (!mIsStart) {
			setLocationOption();
			mLocClient.start();
			mIsStart = true;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mLocClient != null) {
			if (!mLocClient.isStarted()) {
				setLocationOption();
				mLocClient.start();
			}
			mLocClient.requestLocation();
		}
	}

	protected void onPause() {
		if (mLocClient != null) {
			mLocClient.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		missDialog();
//		if (mLocClient != null) {
//			mLocClient.start();
//		}
		if (isLogin()) {
			loginBtn.setText("注销");
		} else {
			loginBtn.setText("登录");
		}
		
		if (!isDialogShowed() && preferences.getInt("isNotPromtAgain", 2) != 0) {
			dialog = new MyDialog(mContext,preferences);
			dialog.setDialog(dialog);
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
			SharedPreferences.Editor editor = preferences.edit();
			editor.putBoolean("isShowed", true).commit();
		} 
		
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mLocClient.stop();
		super.onDestroy();
	}

	// 设置相关参数
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setProdName("DJSearch");
		option.setPoiExtraInfo(true);
		option.setAddrType("all");
		option.setCoorType("bd09ll");//设置坐标类型,百度坐标
		option.setScanSpan(6000);// 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
		// option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
		// option.setPoiNumber(10);默認3
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}
	
	
	private void requestLogin() {
		IRequest request = new JSONReq("login");
		//	{“userId”:”8765”,”password”:”123456”,”recommendPerson”:”king”}
		showDialog("正在登录...");
		request.putParam("userId", preferences.getString("userId", ""));
		request.putParam("password", preferences.getString("userPassWord", ""));
		request.putParam("recommendPerson", "");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					try {
						String returnMessage = response.getString("message");
						Toast.makeText(mContext, returnMessage, 3000).show();
						getDataToResolve(response);
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else if(IResponse.Fail==result){
					//登陆失败
					Toast.makeText(mContext, "shibia", 3000).show();
				}
				missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				super.onFailure(e, response);
				missDialog();
				Toast.makeText(mContext, "登陆失败", 3000).show();
			}
			
		});
	}
		
	
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new Builder(mContext);
			builder.setMessage("确认退出吗？");
		    builder.setTitle("提示");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					/**
					 * 清除登录信息
					 */
					 SharedPreferences.Editor editor = preferences.edit();
					 editor.putBoolean("isShowed", false).commit();
					 startActivity(mContext, null, 1);
				}
			});
	        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});

		    builder.create().show();
		}
		
		return false;
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean("isLogined", true).commit();
		loginBtn.setText("注销");
	}
	
	
	private boolean isDialogShowed() {
		boolean isShowed = preferences.getBoolean("isShowed", false); 
		return isShowed;
	}
}
